﻿@using WebAPP.ViewModels
@using WebAPP.HttpClients
@using Contracts.Services.Catalog
@using Contracts.Abstractions.Paging

@inject ICatalogHttpClient HttpClient
@inject CatalogGridViewModel ViewModel

<div class="row row-cols-md-4">
    @foreach (var card in ViewModel.Cards)
    {
        <BSCol MarginTopAndBottom="Margins.ExtraSmall" Padding="Padding.None">
            <CatalogCard ViewModel="card" OnDeleted="Delete"></CatalogCard>
        </BSCol>
    }
</div>
<BSPagination Align="Align.Center">
    <BSPaginationItem IsDisabled="@(ViewModel.Page.HasPrevious is false)" @onclick="MoveToPreview">Previous</BSPaginationItem>
    @for (var paging = 1; paging <= ViewModel.Page.Current; paging++)
    {
        var current = paging;
        <BSPaginationItem @onclick="() => MoveToPage(current)">@current</BSPaginationItem>
    }
    <BSPaginationItem IsDisabled="@(ViewModel.Page.HasNext is false)" @onclick="MoveToNext">Next</BSPaginationItem>
</BSPagination>


@code {

    private readonly CancellationTokenSource _cancellationTokenSource = new();

    protected override async Task OnInitializedAsync()
        => await FetchDataAsync();

    private async Task FetchDataAsync(int limit = 8, int offset = 0)
    {
        var response = await HttpClient.GetAsync(limit, offset, _cancellationTokenSource.Token);

        if (response.Success)
        {
            ViewModel.Cards = response.ActionResult.Items.Select(catalog => (CatalogCardViewModel) catalog).ToList();
            ViewModel.Page = response.ActionResult.Page;
        }
    }

    public void Add(CatalogCardViewModel card)
    {
        ViewModel.Cards.Add(card);
        StateHasChanged();
    }

    private void Delete(Guid id)
        => ViewModel.Cards.RemoveAll(card => card.Id == id);

    private Task MoveToPage(int current)
        => FetchDataAsync(offset: current - 1);

    private async Task MoveToNext()
    {
        if (ViewModel.Page.HasNext)
            await FetchDataAsync(offset: ViewModel.Page.Current);
    }

    private async Task MoveToPreview()
    {
        if (ViewModel.Page.HasPrevious)
            await FetchDataAsync(offset: ViewModel.Page.Current - 2);
    }

    private void Dispose()
        => _cancellationTokenSource.Cancel();

}